package com.wyl.auth.event;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.wyl.auth.entity.UserLoginLog;
import com.wyl.auth.service.SysMenuService;
import com.wyl.auth.service.UserLoginLogService;
import com.wyl.auth.util.GeoLocationAPI;
import com.wyl.auth.util.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2025/4/13 14:03
 */
@Component
public class UserPermissionEvent {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserLoginLogService userLoginLogService;

    @Async
    @EventListener
    public void doEvent(Long userId) {

        // 权限缓存
        List<String> urlList = sysMenuService.getUrlByUserId(userId);
        redisTemplate.delete("permission:"+userId.toString());
        redisTemplate.opsForSet().add("permission:"+userId, ArrayUtil.toArray(urlList, String.class));

        // 记录登录日志
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserId(userId);
        userLoginLog.setLoginTime(LocalDateTime.now());
        userLoginLog.setSessionId(StpUtil.getTokenValueByLoginId(userId));

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String userAgent = request.getHeader("User-Agent");
        String deviceType = request.getHeader("Sec-Ch-Ua-Platform");
        String ipAddress = IpUtils.getClientIp(request);
        if (StrUtil.isNotBlank(deviceType)) {
            userLoginLog.setDeviceType(deviceType.replaceAll("\"",""));
        }
        userLoginLog.setUserAgent(userAgent);
        userLoginLog.setIpAddress(ipAddress);

        GeoLocationAPI.GeoLocation geoLocation = GeoLocationAPI.getLocation(ipAddress);
        if(geoLocation != null) {
            if(StrUtil.isNotBlank(geoLocation.getLat())&&StrUtil.isNotBlank(geoLocation.getLon())) {
                userLoginLog.setLocation(geoLocation.getLat()+","+geoLocation.getLon());
            }
            userLoginLog.setCountry(geoLocation.getCountry());
            userLoginLog.setProvince(geoLocation.getRegion());
            userLoginLog.setCity(geoLocation.getCity());
        }

        userLoginLog.setLoginResult(1);
        userLoginLogService.save(userLoginLog);
    }
}